/**
 * 路网图类
 */
var Subwaymap = org.gridsofts.util.Class.define({
	name:	"Subwaymap",
	/**
	 * 类静态属性、方法
	 */
	statics: {
		actualWidth: 0,
		actualHeight: 0,

		minWidth:1000000,
		minHeight:1000000,

        sequenceZoom : 0.05,  //依次放大、缩小值
        maxZoom:2,  //最大放大值
        minZoom:0.2, //最小缩小值

        postionX:0,
        postionY:0,

        scale:0,  //缩放比例

		stationClick:"stationClick",
        cutpintClick:"cutpintClick",
        jsonObj : {"stationClick":[],"cutpintClick":[]},

		// 工具集
		utils: {
			obtainPathCoord: function(a) {
				var coord = a + " ";
				for (var i = 1; i < arguments.length - 1; i += 2) {
					coord += arguments[i] + " " + arguments[i + 1] + " ";
				}
				return coord;
			}
		}
	},
	
	/**
	 * 构造函数
	 */
	construct: function(options) {
		if (arguments.length == 0 || typeof(arguments[0]) != "object") {
			throw new Error("Object construct parameter is empty, unable to initialize instance of Subwaymap.");
		}
            // 检查构造参数是否完整
            if (!options.hasOwnProperty("containerId")
                || !options.hasOwnProperty("mapJson")
                || typeof(options["mapJson"]) != "object") {
                throw new Error("The construction parameter lacks the required attributes.");
            }
            // 处理参数
            this.containerId = options["containerId"];
            this.mapJson = options["mapJson"];
            this.qipaoJson=options["qipaoJson"];

            this.type=options["type"];
            this.lljk=null;
            this.light_stage=null;

            // 创建画布
            if(!this.stage){
                this.stage = new Kinetic.Stage({
                    container: this.containerId,
                    draggable: true
                });
            }

            if("highLight_load"==this.type){
                this.highLightJson=options["highLightJson"];
                this.initLine();
                var id=options["id"];
                $("#"+id).show();
                if(!this.light_stage){
                    this.light_stage= new Kinetic.Stage({
                        container: id,
                        draggable: true
                    });
                }
                this.repaint_light();

            }else if("lljk_load"==this.type){
                if(options.hasOwnProperty("lljk")){
                    this.lljk=options["lljk"];
                    this.repaint_lljk();
                }else{
                    throw new Error("获取流量监控数据发生错误");
                }
            }else if("init_load"==this.type){
                this.repaint();
            }
	},

	methods: {

		updateUI: function() {
            var unscaledWidth = arguments[0] ? arguments[0] : 0;
            var unscaledHeight = arguments[1] ? arguments[1] : 0;
            if(this.light_stage!=null){
                this.light_stage.setWidth(unscaledWidth);
                this.light_stage.setHeight(unscaledHeight);
			}
			this.stage.setWidth(unscaledWidth);
			this.stage.setHeight(unscaledHeight);

            Subwaymap.actualWidth += Subwaymap.minWidth;
            Subwaymap.actualHeight += Subwaymap.minHeight;

            var xScale = (this.stage.width()) / Subwaymap.actualWidth;
            var yScale = (this.stage.height()-20) / Subwaymap.actualHeight;

           // Subwaymap.scale = xScale > yScale ? xScale : yScale;
            Subwaymap.scale = xScale < yScale ? xScale : yScale;
			this.stage.scale({ x: Subwaymap.scale, y: Subwaymap.scale });
            this.stage.draw();

            if(this.light_stage!=null){
                this.light_stage.scale({ x: Subwaymap.scale, y: Subwaymap.scale });
                this.light_stage.draw();
			}

            this.moveToCenter();
		},
		getStage:function(){
		  return this.stage;
        },
		/**
		 * 向路网图添加图层
		 */
		addLayer: function(layer) {
			this.stage.add(layer.getLayer());
			return this;
		},
        cacheMapData : function (data) {
			subwaymap.subWaydata.lines = data.lines;
			subwaymap.subWaydata.stations = data.stations;
			subwaymap.subWaydata.icons = data.icons;
        },
		moveToCenter : function () {
            var unscaledWidth = arguments[0] ? arguments[0] : this.stage.getWidth();
            var unscaledHeight = arguments[1] ? arguments[1] : this.stage.getHeight();

            this.stage.setWidth(unscaledWidth);
            this.stage.setHeight(unscaledHeight);

            Subwaymap.postionX=(this.stage.width() / 2 - Subwaymap.actualWidth * Subwaymap.scale / 2);
            Subwaymap.postionY=(this.stage.height() / 2 - Subwaymap.actualHeight * Subwaymap.scale/2 );

            this.stage.position({ x:Subwaymap.postionX, y: Subwaymap.postionY });
            this.stage.draw();

            if(this.light_stage!=null){
                this.light_stage.setWidth(unscaledWidth);
                this.light_stage.setHeight(unscaledHeight);

                this.light_stage.position({ x: (this.light_stage.width() / 2 - Subwaymap.actualWidth * Subwaymap.scale / 2),
                    y: (this.light_stage.height()/2 - Subwaymap.actualHeight * Subwaymap.scale / 2) });

                this.light_stage.draw();
            }
    },

		/**
		 * *******************************
		 * ********以下为私有方法 **********
		 * *******************************
		 */
        repaint_light:function(){
            if(arguments[0]!=null){
                this.highLightJson = arguments[0] ? arguments[0] : this.highLightJson;
            }
            // 清空画布
            this.light_stage.clear();

            // 根据路网图数据，重绘路网线（上行、下行）
            this.paintAllLines(this.light_stage,this.highLightJson["lines"]);

            //根据路网图数据，重绘路网站点
            //  this.paintAllStation(this.light_stage,this.highLightJson["stations"],"highLight");

            //根据网路图数据，重绘网线图 图标
            //   this.paintAllIcons(this.light_stage,this.highLightJson["icons"]);

		},

        repaint_lljk:function(){
            if(arguments[0]!=null && arguments[1]!=null ){
                this.mapJson = arguments[0] ? arguments[0] : this.mapJson;
                this.lljk = arguments[1] ? arguments[1] : this.lljk;
                //进站、出战、换乘 气泡绘制
                this.paintLljkLines(this.lljk["returnData"]);
            }else{
                this.stage.clear();

                // 根据路网图数据，重绘路网线（上行、下行）
                this.paintAllLines(this.stage,this.mapJson["lines"]);

                //请求后台得到流量监控数据
                this.paintLljkLines(this.lljk["returnData"]);

                //根据路网图数据，重绘路网站点
                this.paintAllStation(this.stage,this.mapJson["stations"],"");

                //根据网路图数据，重绘网线图 图标
                this.paintAllIcons(this.stage,this.mapJson["icons"]);
            }
		},
		initLine: function()	 {
			// 清空画布
			this.stage.clear();

			// 根据路网图数据，重绘路网线（上行、下行）
			this.paintAllLines(this.stage,this.mapJson["lines"]);

			//根据路网图数据，重绘路网站点
            this.paintAllStation(this.stage,this.mapJson["stations"],"");

            //根据网路图数据，重绘网线图 图标
            this.paintAllIcons(this.stage,this.mapJson["icons"]);

		},
        repaint: function()	 {
            if(arguments[0]!=null && arguments[1]!=null ){
                this.mapJson = arguments[0] ? arguments[0] : this.mapJson;
                this.qipaoJson = arguments[1] ? arguments[1] : this.qipaoJson;
                //进站、出战、换乘 气泡绘制
                this.paintQipao(this.mapJson["stations"],this.qipaoJson);
            }else{
                // 清空画布
                this.stage.clear();

                this.initLine();

                //进站、出战、换乘 气泡绘制
                this.paintQipao(this.mapJson["stations"],this.qipaoJson);
            }
        },
        /**
         * 绘制所有图标===在一个Layer上
         * @param icons
         */
        paintAllIcons:function(stage,icons){
           if(icons && icons.hasOwnProperty("length") && icons.length>0){
                  if(this.iconLayer){
                      this.iconLayer.repaint(icons);
                  }else{
                      this.iconLayer=new Subwaymap.IconLayer(stage,icons);
                  }
		   }
		},
		/**
		 * 绘制所有线路==每条线路一个layer
		 */
		paintAllLines: function(stage,lines) {
			if (lines && lines.hasOwnProperty("length") && lines.length > 0) {
                for (var i in lines) {
                    new Subwaymap.LineLayer(stage, lines[i]);
                }
			}
		},
        /**
         * 绘制所有站点和站名===在同一个layer上
         * @param stations
         */
        paintAllStation:function(stage,stations,marked){
            if(stations && stations.hasOwnProperty("length") && stations.length>0){
                if(this.stationLayer){
                    this.stationLayer.repaint(stations,marked);
                }else{
                    this.stationLayer=new Subwaymap.StationLayer(stage, stations,marked);
                }
            }
        },
        /**
         * 绘制进出、换乘站 客流气泡===所有气泡在一个layer上
         * @param staions
         * @param qipaos
         */
        paintQipao:function(staions,qipaos){
			if(qipaos && qipaos.hasOwnProperty("length") && qipaos.length > 0){
                if (staions && staions.hasOwnProperty("length") && staions.length > 0){
                        if(this.qipaoLayer){
                            this.qipaoLayer.repaint(qipaos,staions);
                        }else{
                            this.qipaoLayer=new Subwaymap.QipaoLayer(this.stage, qipaos,staions);
                        }
				}
			}
		},
        /**
         * 绘制 流量监控 断面====每个断面一个layer
         * @param lines
         */
        paintLljkLines: function(returnData) {
            if (returnData && returnData.hasOwnProperty("length") && returnData.length > 0) {
                    for (var i in returnData) {
                       new Subwaymap.StationLljkLayer(this.stage, returnData[i],this.mapJson["lines"]);
                    }
            }
        },
	/*	paintHighLineLayerLines: function(lines,mark) {
            if (lines && lines.hasOwnProperty("length") && lines.length > 0) {
                if("line"==mark){
                    for (var i in lines) {
                        new Subwaymap.HighLightLineLayer(this.light_stage, lines[i]);
                    }
                }else if("station"==mark){
                    for (var i in lines) {
                        new Subwaymap.StationLayer(this.light_stage, lines[i]);
                    }
                }

            }
        },*/
	    stagePostion:function(){
            var unscaledWidth = arguments[0] ? arguments[0] : this.stage.getWidth();
            var unscaledHeight = arguments[1] ? arguments[1] : this.stage.getHeight();

            this.stage.setWidth(unscaledWidth);
            this.stage.setHeight(unscaledHeight);

            this.stage.scale({ x: Subwaymap.scale, y: Subwaymap.scale });
            this.stage.draw();
            this.stage.position({ x: Subwaymap.postionX, y: Subwaymap.postionY });
            this.stage.draw();

            if(this.light_stage!=null){
                this.light_stage.setWidth(unscaledWidth);
                this.light_stage.setHeight(unscaledHeight);

                this.light_stage.scale({ x: Subwaymap.scale, y: Subwaymap.scale });
                this.light_stage.draw();
                this.light_stage.position({ x: Subwaymap.postionX, y: Subwaymap.postionY });
                this.light_stage.draw();
            }
        },
        zoomViaMouseWheel : function (e) {
          var pointerPos = this.getEventPosition(e);
          var previousScaleValue = Subwaymap.scale;
          var wheelDelta=e.originalEvent.wheelDelta;
          var detail= e.originalEvent.detail;
			if (wheelDelta) {
				if (wheelDelta > 0) {  //放大0
					if (Subwaymap.scale <= Subwaymap.maxZoom){
                        Subwaymap.scale += Subwaymap.sequenceZoom;
                    }
				} else { //suoxiao
					if (Subwaymap.scale >= Subwaymap.minZoom){
                        Subwaymap.scale -= Subwaymap.sequenceZoom;
                    }
				}
			} else if (detail) {  //ff的事件不同，而且向下向上滚动的值不同
				if (detail > 0) {
                    if (Subwaymap.scale <= Subwaymap.maxZoom){
                        Subwaymap.scale += Subwaymap.sequenceZoom;
                    }
				} else {
                    if (Subwaymap.scale >= Subwaymap.minZoom){
                        Subwaymap.scale -= Subwaymap.sequenceZoom;
                    }
				}
			}
			this.zoomMap(Subwaymap.scale, previousScaleValue, pointerPos);
			e.stopPropagation();
			return false;
    },
    getEventPosition : function (ev) {
		var x, y;
		if (ev.offsetX || ev.offsetX == 0) {
			x = ev.offsetX;
			y = ev.offsetY;
		}
		return { x: x, y: y };
     },
    zoomMap : function (scale, oldScale, pointerPos) {
            var stagePos = this.stage.position();

            var vx = pointerPos.x - stagePos.x;
			var vy = pointerPos.y - stagePos.y;

			var ax = vx / oldScale;
			var ay = vy / oldScale;

			var sx = stagePos.x - ax * (scale - oldScale);
			var sy = stagePos.y - ay * (scale - oldScale);

            Subwaymap.postionX=sx;
            Subwaymap.postionY=sy;

			this.stage.scale({ x: scale, y: scale });
			this.stage.draw();


			this.stage.position({ x: sx, y: sy });
			this.stage.draw();

			if(this.light_stage!=null){
                var light_stagePos = this.light_stage.position();

                var vx = pointerPos.x - light_stagePos.x;
                var vy = pointerPos.y - light_stagePos.y;

                var ax = vx / oldScale;
                var ay = vy / oldScale;

                var sx = light_stagePos.x - ax * (scale - oldScale);
                var sy = light_stagePos.y - ay * (scale - oldScale);

                this.light_stage.scale({ x: scale, y: scale });
                this.light_stage.draw();

                this.light_stage.position({ x: sx, y: sy });
                this.light_stage.draw();

			}
	    },
		addEvent:function(objName,func){
            if("stationClick"!=objName && "cutpintClick"!=objName){
            	alert("只能注册两种事件的监听：stationClick(站点)/cutpintClick(断面)")
				return;
			}
			if("stationClick"==objName){
				alert("111");
                Subwaymap.jsonObj.stationClick.push(func);
			}else if( "cutpintClick"!=objName){
				alert("222");
                Subwaymap.jsonObj.cutpintClick.push(func);
			}
		},
	}
});

